package com.example.shiwu.db.dao.base;

import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.shiwu.manager.DatabaseHelper;

import java.io.File;

public class BaseDaoFactory {

    private final String TAG = "hqk";
    private SQLiteDatabase sqLiteDatabase;

    private String sqliteDatabasePath ="/data/data/com.example.shiwu/databases/shiwu.db";

    private static BaseDaoFactory instance = new BaseDaoFactory();
    private DatabaseHelper databaseHelper;


    //饿汉单例模式
    public static BaseDaoFactory getInstance() {
        return instance;
    }
    public BaseDaoFactory() {
        //读者可随意更改路径以及对应数据库名，这里演示暂时放在根目录
        //sqliteDatabasePath = ContUtils.sqliteDatabasePath;
        //sqliteDatabasePath = ContUtils.sqliteDatabasePath;
        File f_=new File(sqliteDatabasePath);

        if(!f_.getParentFile().exists()){
            Log.e("DBService", "文件夹不存在，新建一个");
            f_.getParentFile().mkdirs();
            f_.setWritable(true);
        }
        sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqliteDatabasePath, null);
        Log.i(TAG, "sqliteDatabasePath : " + sqliteDatabasePath);
        Log.i(TAG, "sqLiteDatabase : " + sqLiteDatabase.getPath());
    }
    // 创建 BaseDao 实例，传入具体 DAO 的 Class
    @SuppressWarnings("unchecked")
    public <T extends BaseDao<?>> T createBaseDao(Class<T> daoClass) {
        try {
            // 通过反射创建 DAO 实例，可在构造时传入 databaseHelper 用于数据库操作
            return daoClass.getConstructor(DatabaseHelper.class).newInstance(databaseHelper);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param clazz
     * @param entityClass
     * @param <R>         我们在这可以把它看成某一个对象，它继承与 BaseDao<T> ，而里面的T 就是下面的那个空对象
     * @param <T>         我们在这可以吧它看成某一个空对象 T
     * @return
     */
    public synchronized <R extends BaseDao<T>, T> R createBaseDao(Class<R> clazz, Class<T> entityClass) {
        BaseDao baseDao = null;
        try {
            baseDao = clazz.newInstance();
            baseDao.init(entityClass, sqLiteDatabase);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        return (R) baseDao;
    }
}

